package com.liu.permission.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ArrayUtil;
import com.liu.common.controller.CommonController;
import com.liu.common.entity.R;
import com.liu.common.entity.enums.PermissionEnum;
import com.liu.permission.entity.base.PermissionInfo;
import com.liu.permission.service.IPermissionInfoService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiuChengLong
 * @since 2022-09-22
 */
@RestController
@RequestMapping("/permission/permissionInfo")
public class PermissionInfoController extends CommonController {

    @Resource
    private IPermissionInfoService permissionInfoService;

    /**
     * 新增权限
     * @param permissionInfo 权限信息
     * @return R
     */
    @PostMapping("/addPermission")
    public R<T> addPermission(@RequestBody PermissionInfo permissionInfo){
        boolean hasPermission = StpUtil.hasPermissionOr(PermissionEnum.ADD_PERMISSION.getCode(), PermissionEnum.IS_ADMIN.getCode());
        if (hasPermission){
            //检查当前新增权限是否已存在
            Boolean isExistence = permissionInfoService.checkPermissionCodeExistence(permissionInfo.getPermissionCode());
            if (isExistence){
                permissionInfo.setCreateBy(this.getUserId());
                boolean savePermission = permissionInfoService.save(permissionInfo);
                if (savePermission){
                    return R.success();
                }else {
                    return R.failed();
                }
            }else {
                return R.failed();
            }
        }else {
            return R.failed();
        }
    }

    /**
     * 获取所有权限
     * @return R
     */
    @GetMapping("/getPermissionList")
    public R<List<PermissionInfo>> getPermissionList(){
        List<PermissionInfo> permissionInfoList = permissionInfoService.list();
        if (ArrayUtil.isNotEmpty(permissionInfoList)){
            return R.success(permissionInfoList);
        }else {
            return R.failed();
        }
    }

}

